package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.mapper.UserMapper;
import com.example.mapper.UserRoleMapper;
import com.example.pojo.PageBean;
import com.example.pojo.User;
import com.example.pojo.UserRole;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author testjava
 * @since 2022-08-20
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;

    /**
     * 查询用户及其权限（可根据id查询）
     * @param uid
     * @return
     */
    @Override
    public List<User> selectUserWithRoles(Integer uid) {
        userMapper.selectUserAndRoles(uid);
        PageBean<User> pageBean = new PageBean<>();

        return userMapper.selectUserAndRoles(uid);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean addUser(User user,Integer[] rolesId) {
        //添加用户
        boolean save = this.save(user);
        //添加用户与部门关系
        boolean isSuccess = userRoleMapper.add(user.getUid(), rolesId);

        return save && isSuccess;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean deleteByUid(Integer uid) {
        //删除用户表数据
        boolean remove = this.removeById(uid);
        //删除用户岗位关系
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(uid != null,UserRole::getUid,uid);
        int delete = userRoleMapper.delete(wrapper);

        return remove && delete > 0;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean updateUserAndRole(User user, Integer[] rolesId) {
        //更新用户
        boolean update = this.updateById(user);
        //删除岗位信息
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(user.getUid() != null, UserRole::getUid, user.getUid());
        userRoleMapper.delete(wrapper);

        //加入新的岗位信息
        boolean add = userRoleMapper.add(user.getUid(), rolesId);
        return update && add;
    }

    @Override
    public User login(String loginName, String password) {
        return userMapper.getUserByLoginNameAndPwd(loginName,password);
    }

    @Override
    public PageBean<User> getPage(Integer uid, Integer currentPage, Integer pageSize) {
        Integer page = (currentPage - 1) * pageSize;
        List<User> userList = userMapper.selectUserWithRolesAndPage(uid,page,pageSize);

        return new PageBean<>(currentPage,pageSize,count(),userList);
    }
}
